package com.pentalog.webservice;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

//import org.jdom2.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

import com.pentalog.bo.StringReveralService;
@Endpoint("spentalog")
public class PentalogEnpoint {
    private static final String NAMESPACE = "http://pentalog.com/testservice/schema";
    @Autowired
	private StringReveralService stringReversalService;

	public void setStringReveralService(
			StringReveralService stringReveralService) {
		this.stringReversalService = stringReveralService;
	}
	@PayloadRoot(namespace = NAMESPACE, localPart = "stringPentalogService")
    @ResponsePayload
    public Element getStringPentalogService() {
		Element responseXml = null;
		String reversedString = invokeServiceAndReturnResponse("tlehuu pentalog");
		responseXml = prepareResponseXml(reversedString);

        return responseXml;
	}
	private String invokeServiceAndReturnResponse(String requestString) {
		String reversedString = stringReversalService.reverse(requestString);
		return reversedString;
	}

	private static Element prepareResponseXml(String responseString) {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		Document document = null;
	    try {
	      DocumentBuilder builder = factory.newDocumentBuilder();
	      document = builder.newDocument();
	    }catch (ParserConfigurationException parserException) {
	      parserException.printStackTrace();
	    }
		Element responseElement = document.createElementNS(NAMESPACE,
				"stringReveralResponse");
		Text responseText = document.createTextNode(responseString);
		responseElement.appendChild(responseText);
		return responseElement;
	}
}
